/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package it.unitn.science.matr155863_148346_145963.bccstore.servlet;

import it.unitn.science.matr155863_148346_145963.bccstore.DBManager;
import it.unitn.science.matr155863_148346_145963.bccstore.items.Product;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.UnavailableException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;

/**
 *
 * @author berto
 */
public class BuyProductSRV extends HttpServlet {

    private DBManager db;
    private static Logger log = Logger.getLogger(BuyProductSRV.class);
    
    @Override
    public void init() throws UnavailableException{
            db=(DBManager)super.getServletContext().getAttribute("db_manager");
    }    
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            String strQuantita = request.getParameter("quantity");              
            if (strQuantita!= null){
                  out.println("<div class=\"content\">");
                  out.println("<h2>Descrizione dell'ordine:</h2>");
                  int quantitaInserita=0;
                  try{                          
                        quantitaInserita = Integer.parseInt(strQuantita);
                        out.println("<p>la quantita che hai inserito è: "+quantitaInserita+".</p>");
                  }catch(Exception ex){
                        out.println("<p>Se vuoi acquistare il prodotto inserisci una quantita valida.</p>");
                        quantitaInserita=0;
                  }if(quantitaInserita > 0){
                        elaborateOrder(request,response,quantitaInserita,out);
                  }else{
                        out.println("<p>inserisci una quantita maggiore di 0.</p>");
                  }
                  out.println("</div>");
            }   
            RequestDispatcher dispatcher=request.getRequestDispatcher("/contents/user/ShowProductDetails?id="+request.getParameter("id"));
            dispatcher.include(request, response);
            Integer id=Integer.parseInt(request.getParameter("id"));
            if(db.getProduct(id)!=null){
                showFormBuy(request,response,out);
            }
        }catch(Exception ex){
            log.error(ex);
            RequestDispatcher dispatcher=request.getRequestDispatcher("/contents/public/errorPage.html");
            dispatcher.include(request, response);
        } finally {            
            //out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private void showFormBuy(HttpServletRequest request,HttpServletResponse response, PrintWriter out) {
        out.println("<form name=\"add_product\" method=\"post\" "
                + "action=\""+response.encodeURL(request.getRequestURL().toString())+"\" >"
                + "<input type=\"hidden\" name=\"id\" "
                        + "value=\""+request.getParameter("id")+"\" "
                    + "/>"
                + "<input type=\"text\" name=\"quantity\" /><label> items</label>"
                + "<input type=\"submit\" name=\"buy\" value=\"Buy\"/>"
                + "</form>");
    }

    private void showFormConferma(HttpServletRequest request,HttpServletResponse response, Integer quantity, PrintWriter out) {
        out.println("<form name=\"conferma\" method=\"post\" "
                + "action=\""+response.encodeURL(request.getContextPath()+"/services/ExecutePurchase")+"\" >"
                + "<input type=\"hidden\" name=\"id\" "
                        + "value=\""+request.getParameter("id")+"\" "
                + "/>"
                + "<input type=\"hidden\" name=\"quantity\" "
                        + "value=\""+quantity+"\" "
                + "/>"
                + "<h3>Confermi l acquisto?</h3>"
                + "<input type=\"submit\" name=\"acquistoConfermato\" value=\"conferma\"/>"
                + "</form>");
    }

    private Product checkDisponibility(HttpServletRequest request,HttpServletResponse response,Integer quantitaRichiesta,Integer id, PrintWriter out) {
        Product prod = db.getProduct(id);
        if(prod.getQuantity()<quantitaRichiesta){
            out.println("<p>Ci sono solo "+prod.getQuantity()+" "+prod.getUmName()+".</p>");
            out.println("<p>Vuoi comprarne "+prod.getQuantity()+"?</p>");
            out.println("<form name=\"add_product\" method=\"post\" "
                        + "action=\""+response.encodeURL(request.getRequestURL().toString())+"\" >"
                        + "<input type=\"hidden\" name=\"id\" "
                        + "value=\""+request.getParameter("id")+"\" "
                        + "/>"
                        + "<input type=\"hidden\" name=\"quantity\" value=\""+prod.getQuantity()+"\"/>"
                        + "<input type=\"submit\" name=\"buy\" value=\"Buy\"/>"
                        + "</form>");
            return null;
        }else{
            return prod;
        }
    }

    private void elaborateOrder(HttpServletRequest request,HttpServletResponse response,Integer quantitaInserita, PrintWriter out) {
        String acquistoConfermato = request.getParameter("acquistoConfermato");
        String idString = request.getParameter("id");
        int idProd=0;
        try{
            idProd = Integer.parseInt(idString);
        }catch(Exception ex){
            idProd=0;
        }   
        Product prod=checkDisponibility(request,response,quantitaInserita,idProd,out);
        if(prod!=null){
            if(acquistoConfermato==null){
                showFormConferma(request,response,quantitaInserita,out);
            }
        }
    }
}
